using System.ComponentModel.Composition;

namespace SS.WPF.Framework.Preference
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    /// <summary>
    /// The class implement IPreferenceService that is used as controller for storing keys
    /// <para>
    /// It uses PreferenceStore as worker to store keys
    /// </para>
    /// </summary>
    [Export(typeof(IPreferenceService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class PreferenceService : IPreferenceService
    {
        /// <summary>
        /// Default storing path
        /// </summary>
        private const string PREFERENCE_FOLDER = @"SS\WpfApp";
        
        /// <summary>
        /// Event that is used to mark that at least a key has been stored
        /// </summary>
        private event PreferenceChangedHandler _preferenceChanged;

        #region Implementation of IPreferenceService

        public event PreferenceChangedHandler PreferenceChanged
        {
            add { this._preferenceChanged += value; }
            remove { this._preferenceChanged -= value; }
        }

        public string PreferenceStorePath
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                                    PREFERENCE_FOLDER);
            }
        }

        public void InvokePreferenceChanged(string key, object newValue)
        {
            if (this._preferenceChanged != null)
            {
                this._preferenceChanged(key, newValue);
            }
        }

        public IPreferenceStore GetPreferenceStore(string key)
        {
            return new PreferenceStore(this)
                       {
                           Key = key
                       };
        }

        #endregion
    }
}